package HousingService.task2.serialization.db_exschange;

import HousingService.task1.actor.Address;
import HousingService.task2.serialization.deserializator.AbstractReader;
import HousingService.task2.serialization.factory.JSNFactory;
import HousingService.task3.dao.HsAddressDao;
import HousingService.task3.dto.HsAddress;
import HousingService.task3.exceptions.HsAddressDaoException;

import java.io.File;
import java.util.List;

/**
 * Imports data into Data Base from file
 *
 * Created by IntelliJ IDEA.
 * User: Linderhof
 * Date: 03.12.2010
 * Time: 13:24:43
 */
public class Importer {
    /**
     * Imports addresses to DB.
     *
     * Before importing, an HsAddressDao instance should be initialized
     * and send as a parameter to importFile() method.     *
     *
     * @param addressDao
     * @param file
     */
    public void importFile(HsAddressDao addressDao, File file) {
        //Reading Addresses into List<Addresses> from file
        JSNFactory factory =
                new JSNFactory();
        AbstractReader reader =
                factory.createReader();
        List<Address> addresses =
                reader.readAddress(file);

        //Creating dto and importing it into DB
        HsAddress dto = new HsAddress();
        for(Address addr : addresses) {
            dto.setAddressId(addr.get_address_id());
            dto.setStreet(addr.get_street());
            dto.setHouse(addr.get_houseNumber());
            dto.setFlat(addr.get_flatNumber());

            try {
                addressDao.insert(dto);
            } catch (HsAddressDaoException e) {
                System.out.println("Error while importing Address DTO!!!");
                System.out.println("Can't import DTO due to primaryKey unique violation!!!");
                System.out.println(dto);
                //e.printStackTrace();
            }
        }//for

    }//importFile()

}//class Importer
